package org.xiaojl.sys.controller;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.xiaojl.common.base.BaseController;
import org.xiaojl.dwz.DwzAjax;
import org.xiaojl.dwz.page.PageBean;
import org.xiaojl.dwz.page.PageParam;
import org.xiaojl.sys.entity.SysRole;
import org.xiaojl.sys.entity.SysUserRole;
import org.xiaojl.sys.service.SysRoleResourceService;
import org.xiaojl.sys.service.SysRoleService;
import org.xiaojl.sys.service.SysUserRoleService;
import org.xiaojl.utils.MybatisPlusPageUtil;
import org.xiaojl.utils.ToolUtil;
import org.xiaojl.utils.WebUtil;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;

/**
 * <p>
 * 系统角色 前端控制器
 * </p>
 *
 * @author xiaojl
 * @since 2017-08-18
 */
@Controller
@RequestMapping("/sys/sysRole")
public class SysRoleController extends BaseController{
	private static final Logger log = LoggerFactory.getLogger(SysRoleController.class);
	private static final String basePagePath = "sys/role/";

	@Autowired
	private SysRoleService sysRoleService;
	@Autowired
	private SysUserRoleService sysUserRoleService;
	@Autowired
	private SysRoleResourceService sysRoleResourceService;
	
	
//	@RequiresPermissions("pms:role:view")
	@RequestMapping("/list")
	public String List(PageParam pageParam, SysRole sysRole, Model model){
		try {
			String orderBy = "";
			boolean isAsc = true;
			Page<SysRole> page = MybatisPlusPageUtil.getPage(pageParam.getPageNum(), 
					pageParam.getNumPerPage(), orderBy, isAsc);
			Page<SysRole> resultPage = sysRoleService.selectPage(page,sysRole);
			
			PageBean<SysRole> pageBean = new PageBean<SysRole>(resultPage.getCurrent(),
					resultPage.getSize(),resultPage.getTotal(),resultPage.getRecords());
			
			model.addAttribute("pageBean", pageBean);
			model.addAttribute("pageParam", pageParam);
			model.addAttribute("sysRole", sysRole);
			
			return basePagePath+"list";
		} catch (Exception e) {
			log.error("查询列表数据出现异常:", e);
			return operateError("获取数据失败", model);
		}
	}
	
	
	/**
	 * 转到添加角色页面 .
	 * 
	 */
//	@RequiresPermissions("pms:role:add")
	@RequestMapping("/addUI")
	public String addUI(Model model) {
		try {
			return basePagePath+"add";
			
		} catch (Exception e) {
			log.error("进入添加页面出现异常:", e);
			return operateError("获取数据失败", model);
		}
	}
	
	/**
	 * 保存新添加的一个角色 .
	 * 
	 */
//	@RequiresPermissions("pms:role:add")
	@RequestMapping("/add")
	public String add(Model model, SysRole sysRole, DwzAjax dwz) {
		try {
			List<SysRole> listByName = sysRoleService.selectList(new EntityWrapper<SysRole>().eq("name",sysRole.getName()));
			if (ToolUtil.isNotEmpty(listByName)) {
				return operateError("角色名【" + sysRole.getName() + "】已存在", model);
			}

			sysRole.setCreateBy(WebUtil.getSessionUser(request).getSysUser().getId());
			sysRoleService.insert(sysRole);
			return operateSuccess(model, dwz);
		} catch (Exception e) {
			log.error("添加数据出现异常:", e);
			return operateError("保存数据失败", model);
		}
	}
	
	/**
	 * 转到角色修改页面 .
	 * 
	 */
//	@RequiresPermissions("pms:role:edit")
	@RequestMapping("/editUI")
	public String editUI(Model model, Long roleId) {
		try {
			SysRole sysRole = sysRoleService.selectById(roleId);
			if (ToolUtil.isEmpty(sysRole)) {
				return operateError("获取数据失败", model);
			}

			model.addAttribute("sysRole",sysRole);
			return basePagePath+"edit";
		} catch (Exception e) {
			log.error("进入编辑页面时，获取数据出现异常:roleId="+roleId, e);
			return operateError("获取数据失败", model);
		}
	}
	
	/**
	 * 保存修改后的角色信息 .
	 * 
	 */
//	@RequiresPermissions("pms:role:edit")
	@RequestMapping("/edit")
	public String edit(Model model, SysRole role, DwzAjax dwz) {
		try {
			Long id = role.getId();

			SysRole sysRole = sysRoleService.selectById(id);
			if (ToolUtil.isEmpty(sysRole)) {
				return operateError("无法获取要修改的数据", model);
			}

			List<SysRole> listByName = sysRoleService.selectList(new EntityWrapper<SysRole>().eq("name",role.getName()));
			if (ToolUtil.isNotEmpty(listByName)) {
				return operateError("角色名【" + role.getName() + "】已存在", model);
			}

			sysRoleService.updateById(role);
			return operateSuccess(model, dwz);
		} catch (Exception e) {
			log.error("保存修改数据出现异常:", e);
			return operateError("保存失败", model);
		}
	}
	
	/**
	 * 删除一个角色
	 * 
	 */
//	@RequiresPermissions("pms:role:delete")
	@RequestMapping("/delete")
	public String delete(Model model, Long roleId, DwzAjax dwz) {
		try {
			SysRole sysRole = sysRoleService.selectById(roleId);
			if (ToolUtil.isEmpty(sysRole)) {
				return operateError("无法获取要删除的角色", model);
			}
			String msg = "";
			// 判断是否有操作员关联到此角色
			List<SysUserRole> urlist = sysUserRoleService.selectList(new EntityWrapper<SysUserRole>().eq("roleId", roleId));
			if (ToolUtil.isNotEmpty(urlist)) {
				msg += "有【" + urlist.size() + "】个用户关联到此角色，要先解除所有关联后才能删除!";
				return operateError(msg, model);
			}
			
			//级联删除
			sysRoleService.deleteWithCascade(roleId);
			return operateSuccess(model, dwz);
		} catch (Exception e) {
			log.error("删除角色信息出现异常:roleId="+roleId, e);
			return operateError("删除失败", model);
		}
	}
	
	
	/**
	 * 分配角色菜单UI：sys_role_resource
	 */
//	@RequiresPermissions("pms:role:assignpermission")
	@RequestMapping("/assignMenuUI")
	public String assignMenuUI(Model model, Long roleId) {

		SysRole sysRole = sysRoleService.selectById(roleId);
		if (ToolUtil.isEmpty(sysRole)) {
			return operateError("无法获取要分配资源的角色", model);
		}
		//查询该角色下的所有菜单
		String resourceIds = sysRoleResourceService.selectResourceIdsByRoleId(roleId);
		
		String resourcesTree = sysRoleService.selectResourcesTreeByAssign(resourceIds);
		
		model.addAttribute("resourceIds", resourceIds);
		model.addAttribute("resourcesTree", resourcesTree);
		model.addAttribute("role", sysRole);
		return basePagePath+"/assignMenu";
	}
	
	@RequestMapping("/assignMenu")
	public String assignMenu(Model model, Long roleId, String selectVal, DwzAjax dwz){
		try {
			SysRole sysRole = sysRoleService.selectById(roleId);
			if (ToolUtil.isEmpty(sysRole)) {
				return operateError("无法获取要资源的角色", model);
			}
			
			sysRoleResourceService.updateRoleResourceByRoleId(roleId,selectVal);
			return operateSuccess(model, dwz);
		} catch (Exception e) {
			log.error("分配角色菜单权限出现异常:roleId="+roleId, e);
			return operateError("分配角色菜单权限失败", model);
		}
		
	}
	
}
